package toy.keli.picmap.model;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Point;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Method;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.security.MessageDigest;

import toy.keli.picmap.R;
import toy.keli.picmap.util.utilCallback;


/**
 * 一些系统调用
 */
public class system {
    /**
     * 实现Android透明状态栏   https://www.jianshu.com/p/e89ee0a77bb5
     */
    public static void setStatusBarFullTransparent(Window window) {
//        Window window = getWindow();
        if (Build.VERSION.SDK_INT >= 21) {//21表示5.0
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        } else if (Build.VERSION.SDK_INT >= 19) {//19表示4.4
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //虚拟键盘也透明
            //getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
    }

    private static Window getWindow() {
        return null;
    }

    public static void fileFind(){

    }

    public static Activity getActivity() {
        Activity window=null;
        return window;
    }

    public static Point getScreenSize(Context context) {
        Point point = new Point();
        ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getSize(point);
        return point;
    }

    //https://blog.csdn.net/zengshuqin/article/details/7169616  ,https://www.jishudog.com/7835/html
    public static void note(Context context,String tText,int ID){
        //实例化Notification
//        Notification n = new Notification(R.drawable.ico,tickerText,System.currentTimeMillis());
        Notification n = new Notification();
        //设置显示图标，该图标会在状态状态栏显示
        int icon = n.icon = R.drawable.ico;
        //设置显示提示信息，该信息会在状态栏显示
        String tickerText=tText;
        //显示时间
        long when = System.currentTimeMillis();
        //实例化intent
        Intent intent = new Intent(context,context.getClass());
        //获取pendingIntent
        PendingIntent pi = PendingIntent.getActivity(context, 0, intent, 0);

        n.icon=icon;
        n.tickerText=tickerText;
        n.when=when;
        //此处采用默认声音
        n.defaults=Notification.DEFAULT_SOUND;
        //n.sound=Uri.parse("file:///sdcard/notification/ringer.mp3");  //使用自定义声音  如果default、sound同时出现，那么sound无效
        //n.sound=Uri.withAppendedPath(Audio.Media.INTERNAL_CONTENT_URI,"6");  //系统自带的铃声

        n.defaults|=Notification.DEFAULT_VIBRATE;       //添加振动
        //n.vibrate=new long[]{0, 100, 200, 300};         //自定义振动形式  第一个参数是开始振动前等待的时间，第二个参数是第一次振动的时间，第三个参数是第二次振动的时间，以此类推，随便定义多长的数组。但是采用这种方法，没有办法做到重复振动。
        n.defaults|=Notification.DEFAULT_LIGHTS;        //使用闪光 下面是自定义
//        notification.ledARGB=0xff00ff00;
//        notification.ledOnMS=300;
//        notification.ledOffMS=1000;
//        notification.flags|=Notification.FLAG_SHOW_LIGHTS;
//        其中ledARGB表示灯光颜色、ledOnMS亮持续时间、ledOffMS暗的时间。
        n.defaults|=n.FLAG_INSISTENT;//让声音、振动无限循环，直到用户响应
//        n.FLAG_AUTO_CANCEL;//通知被点击后，自动消失
//        n.FLAG_NO_CLEAR;//点击’Clear’时，不清楚该通知(QQ的通知无法清除，就是用的这个

        //第二个参数：下拉状态栏时显示的消息标题expandedmessagetitle
        //第三个参数：下拉状态栏时显示的消息内容expandedmessagetext
        //第四个参数：点击该通知时执行页面跳转
//        n.setLatestEventInfo(context,tText,"",pi);
        n.contentIntent=pi;
        //通过Notification Manager发出通知
        NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        //发出通知
        nm.notify(ID,n);
    }

    public static Long time() {
        return Long.valueOf(String.valueOf(System.currentTimeMillis()));
    }

    /**
     * 判断网络连接是否可用
     * @return
     * https://blog.csdn.net/qq_35427437/article/details/80889120
     */
    protected int checkNetworkInfo(Context context) {

        ConnectivityManager con = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkinfo = con.getActiveNetworkInfo();
        if (networkinfo == null || !networkinfo.isAvailable()) {
            // 当前网络不可用
            return 1;
        }
        boolean wifi = con.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
                .isConnectedOrConnecting();
        if (wifi) {
            // 使用wifi上网
            return 2;
        }
        return 3;
    }

    public static class file {
        @SuppressLint("NewApi")
        public static long ctime(String name) {
            FileTime t = null;
            try {
                t = Files.readAttributes(Paths.get(name), BasicFileAttributes.class).creationTime();

                return Long.valueOf(t.toMillis());
            } catch (IOException e) {
                e.printStackTrace();
            }

            return 0;
        }

        public static boolean exists(String path) {
            File file = new File(path);
            return (file.exists() && file.canRead());
        }

        public static long size(String path) {
            File file = new File(path);
            return file.length();
        }

        public static String sizeFormat(String path) {
            return sizeFormat(size(path));
        }

        public static String sizeFormat(Long value) {
            final String[] units = new String[]{"B", "KB", "MB", "GB"};
            int i = 0;
            double v = value;
            while (v / 1024 > 1) {
                i++;
                v /= 1024;
            }
            String result= String.format("%.2f%s", Double.valueOf(value / Math.pow(1024, i)), units[Math.max(0, i)]);
            return result;
        }

        public static boolean put(String path,String data){
            try {
                File file = new File(path);
                FileOutputStream outputStream = new FileOutputStream(file);
                outputStream.write( data.getBytes());
                outputStream.close();
                return true;
            }catch (Exception e){
                e.printStackTrace();
                return false;
            }
        }

        public static String get(String path) {
            try {
                byte[] brt=new byte[(int) size(path)];
                File file = new File(path);
                FileInputStream outputStream = new FileInputStream(file);
                outputStream.read(brt);
                outputStream.close();
                return new String(brt,"UTF-8");
            }catch (Exception e){
                e.printStackTrace();
                return null;
            }
        }

        public static String md5(String file) {
            try {
                byte[] hash;
                byte[] buffer = new byte[8192];
                MessageDigest md = MessageDigest.getInstance("MD5");
                FileInputStream fis = new FileInputStream(file);
                int len;
                while ((len = fis.read(buffer)) != -1) {
                    md.update(buffer, 0, len);
                }
                hash = md.digest();

                //对生成的16字节数组进行补零操作
                StringBuilder hex = new StringBuilder(hash.length * 2);
                for (byte b : hash) {
                    if ((b & 0xFF) < 0x10) {
                        hex.append("0");
                    }
                    hex.append(Integer.toHexString(b & 0xFF));
                }
                return hex.toString();
            } catch (Exception e) {
                e.printStackTrace();
            }

            return "";
        }
    }

    public static void msg(Context context,String str){
        try {
            Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
        }catch (Exception e){}
    }

    public static void copy(Context context,String str){
        //获取剪贴板管理器：
        ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        // 创建普通字符型ClipData
        ClipData mClipData = ClipData.newPlainText("Label", str);
        // 将ClipData内容放到系统剪贴板里。
        cm.setPrimaryClip(mClipData);
    }

    //https://www.pianshen.com/article/7136179278/
    public static String phoneName(){
        String deviceName = "";
        try{
            Class<?> cls = Class.forName("android.os.SystemProperties");
            Object object = (Object) cls.newInstance();
            Method getName = cls.getDeclaredMethod("get", String.class);
            deviceName = (String) getName.invoke(object, "persist.sys.device_name");
        } catch (Exception e){
            e.printStackTrace();
            deviceName= String.format("picmap_" + new time().format("yyyy-MM-dd") );
        }
        return deviceName.replaceAll(" ","_");
    }

    public static void fork(utilCallback.func func){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    func.call();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }
}
